# @Time : 2024-11-06 11:15
# @Author : Fioman 
# @Phone : 13149920693
"""
当我们需要控制程序中一共可以同时运行多少个线程的时候,这个时候使用信号量就比较好用.信号量在创建对象的
时候会设置一共有几个信号量可以同时存在,每次acquire()就累加1,当到达设定值的时候,acquire(),就会阻塞,
直到有线程完成之后调用release(),每调用一次release(),信号量的数量就减少1
"""
import threading
import time


class GetHtmlTherad(threading.Thread):
    def __init__(self, name, url, sema: threading.Semaphore):
        super(GetHtmlTherad, self).__init__()
        self.name = name
        self.sema = sema
        self.url = url

    def run(self):
        print(f"{self.name} start 当前的信号量个数:{self.sema._value}")
        time.sleep(2)
        self.sema.release()
        print(f"{self.name} end 当前的信号量个数: {self.sema._value}")


class GetUrlThread(threading.Thread):
    def __init__(self, name, sema: threading.Semaphore):
        super(GetUrlThread, self).__init__()
        self.name = name
        self.sema = sema

    def run(self):
        for i in range(1, 31):
            self.sema.acquire()
            thread = GetHtmlTherad(f"thread-{i}", f"http://www.baidu.com{i}", self.sema)
            thread.start()


if __name__ == '__main__':
    sema = threading.Semaphore(3)
    getUrlThread = GetUrlThread("getUrlThread", sema)
    getUrlThread.daemon = True
    getUrlThread.start()
    getUrlThread.join()
